<?php

require_once("../models/config.php");
require_once("../ui.php");
require_once("../stats/db.php");
include_once("bar.graph.php");

// if (!isUserViewAuthorized()) {
// 	echo "Unauthorized access";
// 	die();
// }

global $loggedInUser;
global $db;

function createFeelingsCountSQLCommand() {

	$sql = "SELECT User, `feelings`.`Name` AS Feeling, COUNT(*) AS Count
		FROM `debugging_Reports` JOIN `userCake_Users` ON `User` = `userCake_Users`.`User_ID` JOIN `feelings` ON `Feelings` = `feelings`.`Id`
		WHERE (`userCake_Users`.`Group_Id` = " . STANDART_USER_GROUP_ID . ")
		GROUP BY User, `feelings`.`Name`
		ORDER BY `User`, `feelings`.`Id`";

	return $sql;
}

function getFeelingsCount($data, $user, $feeling) {
	if (!key_exists($user, $data)) {
		return 0;
	}
	
	$userData = $data[$user];
	if (!key_exists($feeling, $userData)) {
		return 0;
	}
	
	return $data[$user][$feeling];
}

$sql = createFeelingsCountSQLCommand();
$result = $db->sql_query($sql);
if (!$result) {
	$error = $db->sql_error();
	return;
}

$rows = $db->sql_fetchall();

$data = array();
$users = array();
$feelings = array();

foreach($rows as $i => $row) {
	$user = $row['User'];
	$feeling = $row['Feeling'];
	$count = $row['Count'];
	
	$data[$user][$feeling] = $count;
	$users[$user] = true;
	$feelings[$feeling] = true;
}

// foreach(array_keys($users) as $i => $user) {
// 	$userData = $data[$user];
	
// 	$sum = array_sum($userData);
// 	foreach ($userData as $j => $count) {
// 		$data[$user][$j] = round($count / $sum * 100, 2); 
// 	}
// }

$series = array();
foreach(array_keys($feelings) as $i => $feeling) {
	
	$series[$feeling] = array();
	foreach(array_keys($users) as $i => $user) {

		$count = getFeelingsCount($data, $user, $feeling); 
		$series[$feeling][] = $count;
	}
}

$colors = array(
	array("R"=>70,"G"=>75,"B"=>180),
	array("R"=>122,"G"=>245,"B"=>0),
	array("R"=>245,"G"=>245,"B"=>0),
	array("R"=>255,"G"=>122,"B"=>122));

drawMyStackedBarGraph($series, "Feelings count", array_keys($users), "Participant",
	"Feelings of participants about the debugging session", $colors);

?>